import { defineStore } from "pinia";
import { Login, UserInfo } from "@/api/user";
import type { LoginForm } from "@/api/user/type";
import { ref } from "vue";
import { constantRoute } from "@/router/routes";
import router from "@/router/index";
// import type { UserState } from "./types/types";
let useUserStore = defineStore(
  "User",
  () => {
    const dialog = ref(false);
    const Sts = ref(true);
    let encryptedData = ref<any>("");
    let afterPublicKey = ref<string>();
    let token = ref<any>(sessionStorage.getItem("X-Access-Token"));
    const user: any = {
      roles: [],
      userId: 0,
      nickname: "",
      avatar: "",
      TempUser: "",
      expireTime: "",
      libraryId: "",
    };
    // -----------------------------------------------------
    // 用户信息
    //

    const userInfo = async () => {
      const res = await UserInfo("");
      if (res.code === 200) {
        Object.assign(user, { ...res.data });
        //console.log(res, "userinfo");
      }
    };

    // -----------------------------------------------------
    let menuRoutes = ref(constantRoute);
    const UserLogin = async (data: LoginForm) => {
      const res = await Login(data);
      if (res.code === 200) {
        const responseData = JSON.parse(res.data.data); // 对返回的 data 字段进行 JSON 解析
        token.value = responseData.accessToken;
        //console.log(responseData);
        afterPublicKey.value = responseData.afterPublicKey;
        sessionStorage.setItem("X-Access-Token", responseData.accessToken);
        sessionStorage.setItem("afterPublicKey", responseData.afterPublicKey);
        return "ok";
      } else {
        return Promise.reject(new Error(res.msg));
      }
    };
    const UserLogout = () => {
      token.value = "";
      sessionStorage.removeItem("X-Access-Token");
      sessionStorage.clear();
      localStorage.clear();
      router.push("/login");
    };
    return {
      token,
      menuRoutes,
      user,
      encryptedData,
      afterPublicKey,
      dialog,
      Sts,
      UserLogin,
      userInfo,
      UserLogout,
    };
  },
  {
    persist: true,
  }
);
export default useUserStore;
